<template>
  <div>
    <div class="header-btn">
      <div>新建群发</div>
      <div>
        <el-button :loading="addloading" type="primary" @click="addOrUpdateTask">确认</el-button>
        <el-button plain type="info" @click="goBack">返回</el-button>
      </div>
    </div>
    <div class="wrap g-card" style="margin-bottom: 20px">
      <el-form ref="form" :model="form" :rules="rules" label-position="right" label-width="120px"
               style="position: relative">
        <el-form-item label="群发名称" prop="messageName">
          <el-input v-model="form.messageName" placeholder="请输入" popper-class="minWidth-inp" style="width: 800px">
          </el-input>
        </el-form-item>
        <div v-if="$route.query.flag == '1'">
          <el-form-item prop="digitalEmployeesId">
            <template slot="label">
              <span class="before-hasValue">超级企微</span>
            </template>
            <!--            <check-digital-employee ref="checkDigitalEmployee" v-model="scrmPersonSopUserRels"-->
            <!--                                    :is-single-option.sync="isSingleOption"></check-digital-employee>-->
            <select-supermicro ref="checkDigitalEmployee" v-model="scrmPersonSopUserRels"
                               :is-single-option="isSingleOption"></select-supermicro>
          </el-form-item>
          <el-form-item label="群发对象" prop="addFlag" required>
            <el-radio-group v-model="form.addFlag">
              <el-radio :label="'0'">全部好友</el-radio>
              <el-radio :label="'1'">标签筛选</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item v-if="form.addFlag == '1'" label="目标标签人群" prop="label">
            <template slot="label">
              <span class="before-hasValue">目标标签人群</span>
            </template>
            <!--            <el-select v-model="form.label" clearable placeholder="请选择" multiple style="width: 800px">-->
            <!--              <el-option v-for="item in labelList" :key="item.groupName" :label="item.groupName"-->
            <!--                         :value="item.groupName"/>-->
            <!--            </el-select>-->
            <!--            <el-cascader-->
            <!--              v-model="form.label" :options="labelList" filterable-->
            <!--              :props="labelProps" style="width: 800px"></el-cascader>-->
            <select-table-label ref="selectTableLabel" v-model="form.label"
                                :queryOptions.sync="scrmPersonSopUserRels"></select-table-label>
          </el-form-item>
        </div>
        <el-form-item v-if="$route.query.flag == '2'" class="showRedRules" label="执行员工">
          <el-button class="button-new-tag" size="small" @click="openStaff">
            <svg-icon icon-class="add"/>
            添加员工
          </el-button>
          <div v-if="scrmPersonSopUserRels.length > 0">
            <el-tag v-for="item in scrmPersonSopUserRels" :key="item.userId" closable @close="handleClose(item)">
              {{ item.userName }}
            </el-tag>
          </div>
        </el-form-item>
        <el-form-item v-if="$route.query.flag == '1'" class="conArea" label="群发内容" required>
          <div style="display: flex;flex-direction: column">
            <span
              style="color:#ccc">客户每天最多接收来自同一个企业的管理员的1条群消息，到达接收上限后将无法给该客户推送消息</span>
            <div v-for="(item,index) in form.contents" :key="index">
              <el-input v-model="form.contents[index]" :autosize="{ minRows: 3 }" maxlength="650"
                        placeholder="请添加群发内容"
                        show-word-limit style="width: 800px;margin-bottom: 12px" type="textarea">
              </el-input>
              <i v-if="form.contents.length != 1" class="el-icon-circle-close conIcon" style="margin-left: 8px"
                 @click="form.contents.splice(index, 1)"></i>
              <i v-if="index == form.contents.length - 1" class="el-icon-circle-plus-outline conIcon"
                 style="margin-left: 8px" @click="form.contents.push('')"></i>
            </div>
          </div>
        </el-form-item>
        <el-form-item v-if="$route.query.flag == '2'" class="conArea" label="群发内容" prop="content" required>
          <div style="display: flex;flex-direction: column">
            <span
              style="color:#ccc">客户每天最多接收来自同一个企业的管理员的1条群消息，到达接收上限后将无法给该客户推送消息</span>
            <el-input v-model="form.content" :autosize="{ minRows: 3 }" maxlength="650" placeholder="请添加群发内容"
                      show-word-limit style="width: 800px;margin-bottom: 12px" type="textarea">
            </el-input>
          </div>
        </el-form-item>
        <el-form-item label="添加素材">
          <NormalSelectMaterial :selectedList="form.messageMaterial" @confirmSelect="confirmSelectFn"/>
        </el-form-item>
        <el-form-item label="二维码">
          <NormalQrCode :codeInfo="codeParams" @deleteSeletedQrcode="deleteSeletedQrcode"
                        @selectedSure="qrCodeConfrim"/>
        </el-form-item>
        <div v-if="$route.query.flag == '1'">
          <el-form-item label="发送对象间隔" prop="objectInterval">
            <el-slider
              v-model="form.objectInterval"
              :max="120"
              :min="1"
              range
              style="width: 800px">
            </el-slider>
          </el-form-item>
          <div>
            <span style="margin-left: 120px;margin-right: 30px">{{ form.objectInterval }}</span>
            <span style="color:#082aff" @click="form.objectInterval = [3,5]">使用推荐值</span>
          </div>
          <div style="margin-top: 6px">
            <span
              style="margin-left: 120px;color: #ccc">发送对象间隔是指发送上一个客户最后一条消息完毕到下一个客户第一条消息开始发送的间隔时间</span>
          </div>
          <el-form-item label="发送消息间隔" prop="messageInterval">
            <el-slider
              v-model="form.messageInterval"
              :max="60"
              :min="1"
              range
              style="width: 800px">
            </el-slider>
          </el-form-item>
          <div>
            <span style="margin-left: 120px;margin-right: 30px">{{ form.messageInterval }}</span>
            <span style="color:#082aff" @click="form.messageInterval = [1,5]">使用推荐值</span>
          </div>
          <div style="margin-top: 6px">
            <span
              style="margin-left: 120px;color: #ccc">发送消息间隔是指发送上一个客户第一条消息完毕到第二条消息开始发送的间隔时间</span>
          </div>
        </div>
        <el-form-item label="群发类型" prop="timedTask">
          <el-radio-group v-model="form.timedTask">
            <el-radio label="0">立即发送</el-radio>
            <el-radio label="1">定时发送</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item v-if="form.timedTask == 1" label="发送时间" prop="settingTime" style="width: 30%">
          <el-date-picker v-model="form.settingTime" placeholder="选择日期时间" type="datetime"
                          value-format="yyyy-MM-dd HH:mm:ss">
          </el-date-picker>
        </el-form-item>
      </el-form>
    </div>
    <!-- 新增员工弹窗 -->
    <SelectUser :is-active="'1'" :selectList="dialogList3" :userList="[]" :visible.sync="staffDialog"
                title="添加员工" @confirm="selectUserConfirm"></SelectUser>
  </div>
</template>

<script>
import {queryDeptMsg} from '../../../api/communityOperating/personalSop'
import {addDispatch, coeAddDispatch} from '@/api/dispatchCustomer/index'
import {nameValidate} from '@/utils/validate'
import {getNowTime} from '@/api/getNowTime.js'
import SelectUser from "@/components/SelectUser/index.vue";
import checkDigitalEmployee from "@/components/checkDigitalEmployee.vue";
import selectSupermicro from "@/components/selectSupermicro.vue";
import selectTableLabel from "@/components/selectTableLabel.vue";

export default {
  name: 'addDispatch',
  components: {SelectUser, checkDigitalEmployee, selectSupermicro, selectTableLabel},
  data() {
    return {
      deptIdObj: null,
      taskId: '', // 数据id
      loading: false, // 新增员工弹窗
      staffDialog: false, // 新增员工弹窗
      total: 0,
      form: {
        // 基础设置
        messageName: '', // 任务名称
        content: '',
        contents: [''],
        messageMaterial: [],
        timedTask: '',
        codeState: '',
        settingTime: '',
        addFlag: '0',
        label: [],
        objectInterval: [3, 5],
        messageInterval: [1, 5],
      },
      scrmPersonSopUserRels: [], // 执行员工
      rules: {
        messageName: [
          {
            required: true,
            validator: nameValidate('任务'),
            trigger: 'blur'
          }
        ],
        // label: [
        //   {
        //     required: true,
        //     message: '目标标签人群不能为空',
        //     trigger: 'change'
        //   }
        // ],
        content: [
          {
            required: true,
            message: '群发内容不能为空',
            trigger: 'blur'
          }
        ],
        timedTask: [
          {
            required: true,
            message: '群发类型不能为空',
            trigger: 'change'
          }
        ],
        settingTime: [
          {
            required: true,
            message: '发送时间不能为空',
            trigger: 'change'
          }
        ]
      },
      defaultProps: {
        children: 'children',
        label: 'label'
      },
      dialogList1: [], // 公司架构
      dialogList2: [], // 选择人员
      dialogList3: [], // 已经勾选的人员
      allDialogList: [], // 存放所有的员工，点弹窗确认需要遍历
      allId: [],
      codeParams: {
        qrState: '1',
        qrType: '',
        activityName: '',
        codeUrl: '',
        qrId: ''
      },
      toshowQrcode: false,
      editCodeInfo: {},
      addloading: false, //加载弹窗

      labelList: [], // 目标标签人群枚举
      labelProps: {
        label: 'name',
      },
      isSingleOption: true, //数字员工单选标记
    }
  },
  watch: {
  },
  mounted() {
  },
  methods: {
    // 删除二维码
    deleteSeletedQrcode() {
      this.codeParams.qrType = '';
      this.codeParams.activityName = '';
      this.codeParams.codeUrl = '';
      this.codeParams.qrId = '';
    },
    qrCodeConfrim(data) {
      if (data) {
        this.codeParams = {
          qrState: data.qrState,
          qrType: data.qrType,
          activityName: data.activityName,
          codeUrl: data.qrCode || data.codeUrl,
          qrId: data.qrId
        }
      } else {
        this.codeParams = {
          qrState: 1,
          qrType: '',
          activityName: '',
          codeUrl: '',
          qrId: ''
        }
      }
    },
    // 弹窗的确认
    selectUserConfirm(value) {
      this.staffDialog = false
      this.scrmPersonSopUserRels = []
      value.forEach((item) => {
        this.scrmPersonSopUserRels.push({
          taskId: this.taskId,
          ...item
        })
      })
    },
    // 查询添加员工的信息
    queryDeptMsg() {
      this.dialogList1 = []
      queryDeptMsg().then((res) => {
        if (res.code === 200 && res.data.length) {
          res.data.forEach((item) => {
            this.dialogList1.push({
              id: item.deptId,
              label: item.deptName,
              children: null
            })
          })
        }
      })
    },
    // 添加员工
    add() {
      this.staffDialog = true
    },
    // 添加员工-打开弹窗
    openStaff() {
      this.dialogList3 = this.scrmPersonSopUserRels || []
      this.staffDialog = true
    },
    // 删除已选人员,执行员工
    handleClose(item) {
      this.scrmPersonSopUserRels = this.scrmPersonSopUserRels.filter((x) => {
        return x.userId != item.userId
      })
    },
    // 确认
    addOrUpdateTask() {
      this.form.messageMaterial.forEach(item => {
        if (item.mediaType == '3') {
          item.materialUrl = window.globalConfig.SHARE_URL + '/linkFile?id=' + item.id
        } else if (item.mediaType == '4') {
          item.materialUrl = window.globalConfig.SHARE_URL + '/linkArticle?id=' + item.id
        } else if (item.mediaType == '10') {
          item.materialUrl = window.globalConfig.SHARE_URL + '/linkForm?id=' + item.id
        } else if (item.mediaType == '7') {
          if (item?.content == '6') {
            item.materialUrl = window.globalConfig.SHARE_URL + '/linkVideo?id=' + item.id
          }
        }
      })
      let sender = ''
      if (this.$route.query.flag == '1') {

      } else if (this.$route.query.flag == '2') {
        this.scrmPersonSopUserRels.forEach(item => {
          sender += item.userId + ','
        })
      }
      sender = (sender.substring(sender.length - 1) == ',') ? sender.substring(0, sender.length - 1) : sender
      this.$refs['form'].validate((valid) => {
        if (valid) {
          if (this.scrmPersonSopUserRels.length === 0 && this.$route.query.flag == '2') {
            this.$message.error('请选择执行员工')
            return
          }
          if (this.scrmPersonSopUserRels.length === 0 && this.$route.query.flag == '1') {
            this.$message.error('请选择超级企微')
            return
          }
          if (this.form.addFlag == '1' && (!this.form.label || this.form.label.length == 0) && this.$route.query.flag == '1') {
            this.$message.error('请选择目标标签人群')
            return;
          }
          if (this.form.contents.indexOf('') > -1 && this.$route.query.flag == '1') {
            this.$message.error('存在空的群发内容')
            return
          }
          if (+this.codeParams.qrState === 0 && !this.codeParams.activityName) {
            this.$message.error("请选择二维码！")
            return
          }
          if (this.form.timedTask == '0') this.form.settingTime = getNowTime()
          this.form.codeState = this.codeParams.qrState;
          let obj = {
            ...this.form,
            messageCode: [this.codeParams],
            sendWeUsers: this.scrmPersonSopUserRels,
            sender,
            chatType: '0',
            label: this.form.label ? this.form.label.map(item => item.id) : null,
            objectInterval: this.form.objectInterval ? JSON.stringify(this.form.objectInterval) : '',
            messageInterval: this.form.messageInterval ? JSON.stringify(this.form.messageInterval) : '',
            edition: this.$route.query.flag == '2' ? '1' : '2',
            addFlag: this.$route.query.flag == '1' ? this.form.addFlag : null,
          }
          this.addloading = true
          if (this.$route.query.flag == '1') {
            coeAddDispatch(obj).then((res) => {
              if (res.code === 200) {
                this.$message.success('新增成功')
                this.addloading = false
                this.$router.push({
                  name: 'DispatchCustomer',
                  query: {
                    activeName: this.$route.query.activeName
                  }
                })
              }
            }).catch(() => {
              this.addloading = false
            })
          } else if (this.$route.query.flag == '2') {
            addDispatch(obj).then((res) => {
              if (res.code === 200) {
                this.$message.success('新增成功')
                this.addloading = false
                this.$router.push({
                  name: 'DispatchCustomer',
                  query: {
                    activeName: this.$route.query.activeName
                  }
                })
              }
            }).catch(() => {
              this.addloading = false
            })
          }
        } else {
          this.$message.error('您还未录入完成，请核对后提交！')
        }
      })
    },
    // 返回
    goBack() {
      this.$router.push({
        name: 'DispatchCustomer',
        query: {
          activeName: this.$route.query.activeName,
        }
      })
    },

    //选择二维码
    showSelectCode(val) {
      val == 0 ? this.toshowQrcode = true : this.toshowQrcode = false
      // this.qrCodeList = {qrType:1}
    },
    // 确定选择的素材
    confirmSelectFn(val) {
      this.form.messageMaterial = val;
    },
  }
}
</script>

<style lang="scss" scoped>
@import "../../../styles/base.scss";

.header-btn {
  @include headerBtn;
}

.wrap {
  @include titleWrap;
}

.dialog-wrap {
  display: flex;
  justify-content: flex-start;

  .dialog-list {
    width: 33%;
    padding: 0 15px;
    box-sizing: border-box;
    max-height: 500px;
    overflow: auto;

    &:nth-child(2) {
      flex: 1;
      border-left: $normalBorder;
      border-right: $normalBorder;
    }
  }

  .block-wrap {
    display: flex;
    justify-content: flex-start;
    flex-wrap: wrap;
    font-weight: 600;
    color: #2a2a2a;
    font-size: 12px;
    font-family: PingFangSC-Medium, PingFang SC;

    .block-item {
      width: 80px;
      padding: 5px 0;
      margin: 10px;
      border: $normalBorder;
      text-align: center;

      .svg-icon {
        width: 4em;
        height: 3em;
        vertical-align: -0.15em;
        fill: currentColor;
        overflow: hidden;
      }
    }
  }

  .upload-list {
    display: flex;
    justify-content: space-between;
    border: $normalBorder;
    padding: 0 10px;
  }
}

.copy-card {
  width: 740px;
  background-color: #fafafa;
  position: relative;
  margin: 10px;

  .content-item {
    width: 400px;
    background-color: #e9e9e9;
    padding: 0 10px;
    margin-bottom: 10px;
    display: flex;
    justify-content: space-between;
  }

  .copy-edit {
    position: absolute;
    top: 20px;
    right: 20px;
  }

  .right-close {
    position: absolute;
    right: -2px;
    top: -2px;
  }
}

// 必录框前面的'*'
.showRedRules {
  ::v-deep.el-form-item__label:before {
    content: "*";
    color: #e74e59;
    margin-right: 4px;
  }
}

.before-hasValue::before {
  content: "*";
  color: #e74e59;
  margin-right: 4px;
}

::v-deep.el-slider__runway.el-slider__button-wrapper > .el-slider__button {
  width: 12px;
  height: 12px;
}

::v-deep.el-popper.el-cascader__dropdown {
  min-width: 220px;
}

.conIcon {
  font-size: 32px;
  cursor: pointer;
  color: #082aff;
}
</style>
